//
//  UTSNetwork.swift
//  UTSNetwork
//
//  Created by Admin on 2024/8/2.
//

import UIKit
import Alamofire

public func getDesition(_ fileDir: String?, fileName: String?)-> DownloadRequest.Destination? {
    let destination: DownloadRequest.Destination? = { (temporaryURL: URL, response: HTTPURLResponse) in
        var fileURL = temporaryURL
        if let dir = fileDir, let name = fileName {
            let dirStr = formatDir(dir: dir)
            fileURL = URL(fileURLWithPath: "\(dirStr)/\(name)")
        } else if let name = fileName {
            var dirStr = temporaryURL.deletingLastPathComponent().absoluteString
            dirStr = formatDir(dir: dirStr)
            fileURL = URL(fileURLWithPath: "\(dirStr)/\(name)")
        } else if let dir = fileDir {
            var dirStr = dir
            dirStr = formatDir(dir: dirStr)
            if let suggestedFilename = response.suggestedFilename {
                fileURL = URL(fileURLWithPath: "\(dirStr)/\(suggestedFilename)")
            }
        } else if let suggestedFilename = response.suggestedFilename {
            var dirStr = temporaryURL.deletingLastPathComponent().absoluteString
            dirStr = formatDir(dir: dirStr)
            fileURL = URL(fileURLWithPath: "\(dirStr)/\(suggestedFilename)")
        }
        let option: DownloadRequest.Options = [.removePreviousFile, .createIntermediateDirectories]
        return (fileURL, option)
    }
    return destination
}

func formatDir(dir: String)-> String {
    var dirValue = dir
    let endStr = "file://"
    if dirValue.hasPrefix(endStr) {
        dirValue = String(dirValue[dirValue.index(dirValue.startIndex, offsetBy: endStr.count)..<dirValue.endIndex])
    }
    if dirValue.hasSuffix("/") {
        dirValue = String(dirValue[dirValue.startIndex..<dirValue.index(dirValue.endIndex, offsetBy: -1)])
    }
    return dirValue
}

//public typealias UTSNetworkErrorHandle = (_ error: Error) -> Void
//public typealias UTSNetworkSucHandle = (_ response: String?, _ header:  [AnyHashable : Any]?) -> Void
//public typealias UTSNetworkDownloadHandle = (_ response: URL?, _ header:  [AnyHashable : Any]?) -> Void
//
//public class UTSNetwork: NSObject {
//    
//    public static func request(_ convertible: URLConvertible,
//                     method: HTTPMethod = .get,
//                     parameters: Parameters? = nil,
//                     encoding: ParameterEncoding = URLEncoding.default,
//                     headers: HTTPHeaders? = nil,
//                     interceptor: RequestInterceptor? = nil,
//                     requestModifier: Session.RequestModifier? = nil,
//                     errorHandle: UTSNetworkErrorHandle? = nil,
//                     sucHandle: UTSNetworkSucHandle? = nil
//                               
//    ) {
//      let dataRequest = AF.request(convertible, method: method, parameters: parameters, encoding: encoding, headers: headers, interceptor: interceptor, requestModifier: requestModifier)
//      dataRequest.responseString { (response: AFDataResponse<String>) in
//            switch response.result {
//            case .success:
//                sucHandle?(response.value,  response.response?.allHeaderFields)
//                break
//            case .failure(let error):
//                errorHandle?(error)
//                break
//            }
//        }
//    }
//    
//    public static func download(_ convertible: URLConvertible,
//                                method: HTTPMethod = .get,
//                                parameters: Parameters? = nil,
//                                encoding: ParameterEncoding = URLEncoding.default,
//                                headers: HTTPHeaders? = nil,
//                                interceptor: RequestInterceptor? = nil,
//                                requestModifier: Session.RequestModifier? = nil,
//                                to destination: DownloadRequest.Destination? = nil,
//                                errorHandle: UTSNetworkErrorHandle? = nil,
//                                sucHandle: UTSNetworkDownloadHandle? = nil
//    ) {
//        
//        let destination = { (temporaryURL: URL, response: HTTPURLResponse) in
//            response.suggestedFilename
//            let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
//            let fileURL = documentsURL.appendingPathComponent("image.png")
//            let option: DownloadRequest.Options = [.removePreviousFile, .createIntermediateDirectories]
//            return (fileURL, option)
//        }
//        let dataRequest = AF.download(convertible, method: method,parameters: parameters, encoding: encoding, headers: headers, requestModifier: requestModifier)
//        dataRequest.downloadProgress(closure: )
//        dataRequest.downloadProgress { progress in
//                    print("Download Progress: \(progress.fractionCompleted)")
//                }
//        dataRequest.response(completionHandler: )
//        dataRequest.response { (response: AFDownloadResponse<URL?>) in
//            debugPrint(response)
//           
//            response.error.debugDescription
//             if response.error == nil, let imagePath = response.fileURL?.path {
//                 let image = UIImage(contentsOfFile: imagePath)
//             }
//        }
//    }
//    
//    static func getDesition(dir: String, fileName: String?) -> (destinationURL: URL, options: DownloadRequest.Options) {
//       let m = HTTPMethod(rawValue: "".uppercased())
//        m
//    }
//}
